<?php
namespace app\admin\controller;
use app\admin\collection\permissionCollection;
use app\admin\model\UserRole;
use app\admin\model\Users;
use app\admin\model\Posts;
use think\Db;
use app\admin\controller\AdminAuth;
use think\Validate;
use think\Loader;

class IndexController extends AdminAuth
{
    //模块基本信息
    private $data = array(
        'module_name' => '起始页',
        'module_url'  => '/admin/Index/',
        'module_slug' => 'Index',
        'upload_path' => UPLOAD_PATH,
        'upload_url'  => '/public/uploads/',
    );

    public function index()
    {
        $this->data['admin_count'] = Users::where('status','=',1)->count();
        $this->data['post_count_all'] = Posts::where('status','>=',0)->count();
        $this->data['post_count_latest_month'] = Posts::whereTime('create_time','>=',date('Y-m-01'))->where('status','>=',0)->count();
        $this->assign('data',$this->data);
        return $this->fetch();
    }

    public function login()
    {
        $this->view->engine->layout(false);
        return view();
    }

    public function login_action(){

        $user = new Users;
        $data = input('post.');
        $rule = [
            //管理员登陆字段验证
            'admin_username|管理员账号' => 'require|min:5',
            'admin_password|管理员密码' => 'require|min:5',
        ];
        // 数据验证
        $validate = new Validate($rule);
        $result   = $validate->check($data);
        if(!$result){
            return $validate->getError();
        }

        $preview = $user->where(array('username'=>$data['admin_username'],'status'=>1))->find();
        if(!$preview){
            $this->error('用户不存在');
        }

        $where_query = array(
                'username' => $data['admin_username'],
                'password' => (isset($preview['salt']) && $preview['salt']) ? md5($data['admin_password'].$preview['salt']) : md5($data['admin_password']),
                'status'   => 1
            );
        if ($user = $user->where($where_query)->find()) {
            //注册session
            session('uid',$user->id);
            session('is_admin',$user->is_admin);
            session('admin_username',$user->username);
            session('admin_password',$user->password);
            session('admin_nickname',$user->nickname);

            if($user->is_admin == 0){
                //查询当前用户权限列表
                $user_permission = permissionCollection::getUserPermissionByUserId($user->id);
                session('user_permission',$user_permission['permission_id']);

                //查询当前用户的部门及角色
                $user_group_role = UserRole::where('user_id','=',$user->id)->find();
                session('user_group',$user_group_role->group_id);
                session('user_role', $user_group_role->role_id);
            }else{
                $user_permission = permissionCollection::getAllPermission();
                session('user_permission',$user_permission);
            }


            //更新最后请求IP及时间
            $request = request();
            $ip = $request->ip();
            $city = $this->getcity();
            $time = time();
            $expire_time = time()+config('auth_expired_time');
            $user->where($where_query)->update(['last_login_ip' => $ip, 'last_login_time' => $time,'expire_time'=>$expire_time]);
            Db::name('user_log')->insert(['user_id'=>$user->id,'log_info'=>'后台登陆','log_ip'=>$ip,'log_city'=>$city,'log_time'=>time()]);

            return $this->success('登录成功', '/admin');
        } else {
            $this->error('登录失败:账号或密码错误');
        }
    }

    /**
     * [lost_password TODO：密码重置功能]
     * @return [type] [description]
     */
    public function lost_password(){
        $this->view->engine->layout(false);
        return view();
    }
    /**
     * [logout 登出操作]
     * @return [type] [description]
     */
    public function logout(){
        $request = request();
        session(null);
        return $this->success('已成功登出', '/admin/login');
    }
    //根据ip获取 城市名
    public function getcity(){
        $request = request();
        $ip = $request->ip();
        $url='http://ip.taobao.com/service/getIpInfo.php?ip='.$ip;
        $result = file_get_contents($url);
        $result = json_decode($result,true);
        $city = $result['data']['city'];
        return $city;

    }
}
